package com.oa.srms.apps.business.student.impl;

import org.springframework.beans.factory.annotation.Autowired;

import com.oa.srms.apps.business.student.IMailInfoService;
import com.oa.srms.apps.constants.IDEDStates;
import com.oa.srms.apps.dao.student.IMailInfoDao;
import com.oa.srms.apps.entity.student.MailInfoValue;

public class MailInfoServiceImpl implements IMailInfoService {
	@Autowired
	private MailInfoValue mailInfoValue;
	@Autowired
	private IMailInfoDao mailInfoDao;

	@Override
	public Integer addMailInfo(String mail) throws Exception {
		mailInfoValue.setMail(mail);
		mailInfoValue.setVerifyCode(this.getVerifyCode());
		mailInfoValue.setStates(IDEDStates.DISABLE);
		return mailInfoDao.addMailInfo(mailInfoValue);
	}

	@Override
	public void modifyMailInfo(Integer mailId, String mail)
			throws Exception {
		mailInfoValue = this.queryByMailId(mailId);
		if (mailInfoValue != null) {
			mailInfoValue.setMail(mail);
			mailInfoValue.setVerifyCode(this.getVerifyCode());
			mailInfoValue.setStates(IDEDStates.DISABLE);
			mailInfoDao.editMailInfo(mailInfoValue);
		}

	}
	
	@Override
	public void modifyMailVerifyCode(Integer mailId) throws Exception {
		mailInfoValue = this.queryByMailId(mailId);
		if (mailInfoValue != null) {
			mailInfoValue.setVerifyCode(this.getVerifyCode());
			mailInfoValue.setStates(IDEDStates.ENABLE);
			mailInfoDao.editMailInfo(mailInfoValue);
		}
	}
	
	private String getVerifyCode() {
		// 随机产生一个16位的验证码
		String sourcenum = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
		String siglenum = "";
		// 该变量保存验证码
		String verifyCode = "";
		for (int i = 0; i < 16; i++) {
			int index = (int) (Math.random() * 100) % 61;
			siglenum = sourcenum.substring(index, index + 1);
			verifyCode += siglenum;
		}
		return verifyCode;
	}

	@Override
	public MailInfoValue queryByMailId(Integer mailId) throws Exception {
		return mailInfoDao.queryByMailId(mailId);
	}

	@Override
	public MailInfoValue queryByMailAndVerifyCode(String mail, String verifyCode)
			throws Exception {
		if(mail != null && verifyCode != null)
			mailInfoValue= mailInfoDao.queryByMailAndVerifyCode(mail, verifyCode);
		
		if(mailInfoValue != null){
			mailInfoValue.setVerifyCode(this.getVerifyCode());
			mailInfoValue.setStates(IDEDStates.ENABLE);
			mailInfoDao.editMailInfo(mailInfoValue);
			return mailInfoValue;
		}
		return null;
	}

}
